package com.example.smart.room.repository

import com.example.smart.room.bean.AnimalBean
import com.example.smart.room.dao.AnimalDAO
import com.example.smart.room.repository.base.BaseRepository
import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.withContext

class AnimalRepository(private val animalDAO: AnimalDAO) : BaseRepository() {

    fun insert(data: AnimalBean) {
        launch {
            animalDAO.insert(data)
        }
    }

    fun update(data: AnimalBean) {
        launch {
            animalDAO.update(data)
        }
    }

    fun getAllData(result: (MutableList<AnimalBean>) -> Unit) {
        launch {
            val allData = animalDAO.getAllData()
            withContext(Dispatchers.Main) {
                result.invoke(allData)
            }
        }
    }

    fun getData(id: Long, result: (AnimalBean) -> Unit) {
        launch {
            val data = animalDAO.getData(id)
            if (data != null) {
                withContext(Dispatchers.Main) {
                    result.invoke(data)
                }
            }
        }
    }

    fun delete(id: Long) {
        launch {
            animalDAO.delete(id)
        }
    }
}